<template>
  <view class="foreign-vehicles-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="true" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="外地车查询" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <!-- 筛选条件 -->
          <view class="filter-section">
            <!-- 停车时长范围 -->
            <view class="filter-item">
              <text class="filter-label">停车时长范围：</text>
              <view class="time-picker">
                <uni-datetime-picker type="daterange" :border="false" v-model="searchForm.dateRange" @change="handleDateRangeChange"></uni-datetime-picker>
              </view>
            </view>
            
            <!-- 订单状态筛选 -->
            <view class="filter-item">
              <text class="filter-label">订单状态：</text>
            </view>
            <up-tabs :list="statusList" :scrollable="false" @change="handleTabChange"></up-tabs>
            
            <!-- 停车场搜索 -->
            <view class="filter-item">
              <up-search v-model="searchForm.parkingLot" :clearabled="true" :showAction="true" 
                placeholder="请输入停车场" @search="handleSearch" @clear="handleClear">
                <template #action>
                  <up-button type="primary" size="small" @click="handleSearch">搜索</up-button>
                </template>
              </up-search>
            </view>
          </view>
        </up-sticky>
      </template>

      <!-- 汇总数据 -->
      <view v-if="summaryData" class="summary-section">
        <view class="summary-item">
          <text class="summary-label">外地车总数</text>
          <text class="summary-value count">{{ summaryData.totalCount }}辆</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">平均停车时长</text>
          <text class="summary-value">{{ summaryData.avgParkingHours }}小时</text>
        </view>
        <view class="summary-item">
          <text class="summary-label">总欠费金额</text>
          <text class="summary-value amount">¥{{ summaryData.totalAmount }}</text>
        </view>
      </view>

      <!-- 列表内容 -->
      <view class="foreign-vehicles-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index" @click="viewDetail(item)">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.plateNumber }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">在停位置：</text>
                <text class="value">{{ item.parkingLot }}</text>
              </view>
              <view class="item">
                <text class="label">驶入时间：</text>
                <text class="value">{{ item.entryTime }}</text>
              </view>
              <view class="item">
                <text class="label">停车时长：</text>
                <text class="value">{{ item.parkingHours }}</text>
              </view>
              <view class="item">
                <text class="label">总欠费金额：</text>
                <text class="value amount">¥{{ item.totalAmount }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

// 状态列表
const statusList = [
  { name: '全部' },
  { name: '在停' },
  { name: '已驶出' },
];
const currentStatus = ref(0);

// 搜索表单
const searchForm = reactive({
  dateRange: [], // 停车时长日期范围
  parkingLot: '',
  status: 0, // 0: 全部, 1: 在停, 2: 已驶出
});

// 处理日期范围变化
const handleDateRangeChange = (e) => {
  searchForm.dateRange = e;
  paging.value?.reload();
};

// z-paging 组件引用
const paging = ref(null);

// 当前列表数据
const currentList = ref([]);

// 汇总数据
const summaryData = ref({
  totalCount: 0,
  avgParkingHours: '0',
  totalAmount: '0.00'
});

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentStatus.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentStatus.value = newIndex;
  searchForm.status = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理搜索
const handleSearch = () => {
  paging.value?.reload();
};

// 处理清除
const handleClear = () => {
  searchForm.parkingLot = '';
  searchForm.dateRange = [];
  paging.value?.reload();
};

// 查询列表数据
const queryList = async (pageNo, pageSize) => {
  try {
    // 处理日期范围参数
    const params = {
      pageNo,
      pageSize,
      parkingLot: searchForm.parkingLot,
      status: searchForm.status
    };
    
    // 如果有日期范围，添加到参数中
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0];
      params.endDate = searchForm.dateRange[1];
    }
    
    // 模拟API调用
    // 实际项目中应替换为真实API
    // const result = await getForeignVehiclesList(params);
    // const data = result.data;
    
    // 模拟数据
    const mockData = {
      total: 100,
      list: Array.from({ length: 10 }, (_, i) => ({
        id: `${pageNo}-${i}`,
        plateNumber: `京${String.fromCharCode(65 + Math.floor(Math.random() * 26))}${Math.floor(Math.random() * 10000).toString().padStart(5, '0')}`,
        parkingLot: `${['首都机场', '北京南站', '西单商场', '王府井'][Math.floor(Math.random() * 4)]}停车场`,
        entryTime: `2023-${Math.floor(Math.random() * 12) + 1}-${Math.floor(Math.random() * 28) + 1} ${Math.floor(Math.random() * 24)}:${Math.floor(Math.random() * 60)}:${Math.floor(Math.random() * 60)}`,
        parkingHours: `${Math.floor(Math.random() * 100)}小时${Math.floor(Math.random() * 60)}分钟`,
        totalAmount: (Math.random() * 200).toFixed(2)
      }))
    };
    
    // 更新汇总数据
    updateSummaryData(mockData.list);
    
    // 通知z-paging组件数据加载完成
    paging.value.complete(mockData.list);
  } catch (error) {
    console.error('获取外地车列表数据失败:', error);
    paging.value.complete(false);
  }
};

// 更新汇总数据
const updateSummaryData = (list) => {
  if (!list || list.length === 0) return;
  
  // 计算总欠费金额
  const totalAmount = list.reduce((sum, item) => sum + parseFloat(item.totalAmount), 0).toFixed(2);
  
  // 计算平均停车时长 (简化处理，实际应该转换为小时再计算)
  const avgHours = (list.reduce((sum, item) => {
    const hours = parseInt(item.parkingHours.split('小时')[0]);
    return sum + hours;
  }, 0) / list.length).toFixed(1);
  
  summaryData.value = {
    totalCount: list.length,
    avgParkingHours: avgHours,
    totalAmount: totalAmount
  };
};

// 查看详情
const viewDetail = (item) => {
  uni.navigateTo({
    url: `/pages/foreign-vehicles/detail?id=${item.id}`
  });
};

// 返回按钮处理
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  });
};

onMounted(() => {
  // 初始化加载数据
  paging.value?.reload();
});
</script>

<style lang="scss" scoped>
.foreign-vehicles-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  
  .filter-section {
    margin-bottom: 10px;
    
    .filter-item {
      margin-bottom: 10px;
      
      .filter-label {
        font-size: 14px;
        color: #333;
        margin-bottom: 5px;
        display: block;
      }
      
      .time-range {
        display: flex;
        align-items: center;
        
        .range-separator {
          margin: 0 10px;
        }
      }
      
      .time-picker {
        background-color: #fff;
        border-radius: 4px;
        padding: 8px 12px;
        box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
        width: 100%;
      }
    }
  }
  
  .summary-section {
    display: flex;
    justify-content: space-between;
    padding: 15px;
    background-color: #fff;
    border-radius: 8px;
    margin: 0 15px 15px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
    
    .summary-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .summary-label {
        font-size: 12px;
        color: #666;
        margin-bottom: 5px;
      }
      
      .summary-value {
        font-size: 16px;
        color: #333;
        font-weight: bold;
        
        &.amount {
          color: #f56c6c;
        }
        
        &.count {
          color: #409eff;
        }
      }
    }
  }
  
  .foreign-vehicles-list {
    padding: 0 15px;
    
    .list-item-card {
      background-color: #fff;
      border-radius: 8px;
      margin-bottom: 15px;
      overflow: hidden;
      box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
      
      .card-header {
        padding: 12px 15px;
        border-bottom: 1px solid #eee;
        
        .title {
          font-size: 14px;
          color: #333;
          
          .number {
            font-weight: bold;
            color: #409eff;
          }
        }
      }
      
      .card-content-box {
        padding: 15px;
        
        .content {
          .item {
            display: flex;
            margin-bottom: 10px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .label {
              width: 90px;
              font-size: 14px;
              color: #666;
            }
            
            .value {
              flex: 1;
              font-size: 14px;
              color: #333;
              
              &.amount {
                color: #f56c6c;
                font-weight: bold;
              }
            }
          }
        }
      }
    }
  }
}
</style>